# coding=UTF-8
import io
import urllib.parse

from docx import Document
from docxcompose.composer import Composer
from docx.enum.section import WD_ORIENTATION
import sys


def merge_doc(source_file_path_list, target_file_path):
    # 定义新文档
    target_doc = Document(source_file_path_list[0])
    section = target_doc.add_section()  # 添加连续的节
    section.orientation = WD_ORIENTATION.PORTRAIT  # 设置纵向
    target_composer = Composer(target_doc)

    for i in range(len(source_file_path_list)):
        # 跳过第一个作为模板的文件
        if i == 0:
            continue

        # 拼接文档内容
        page = Document(source_file_path_list[i])
        if "5e6f53cc02f254f1035ff0400be9bf90.docx" in source_file_path_list[i]:
            section = page.add_section()
            section.orientation = WD_ORIENTATION.LANDSCAPE  # 设置横向
        elif i < len(source_file_path_list) - 1:
            # 设置连续的节
            section = page.add_section()
            section.orientation = WD_ORIENTATION.PORTRAIT  # 设置纵向

        target_composer.append(page)

    target_composer.save(target_file_path)
    print(True)


if __name__ == '__main__':
    # source_path = r"D:\\phpstudy_pro\\WWW\\tool.xmjuncheng.com\\py\\注册资本"
    # target_path = r"C:\\Users\\admin\\Desktop\\对接\\注册资本\\target.docx"
    # source_file_list = os.listdir(source_path)

    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

    # # 接收参数 模板文件数组
    source_file_list = urllib.parse.unquote(sys.argv[1]).split(',')

    # # 生成文件路径
    target_path = urllib.parse.unquote(sys.argv[2])
    merge_doc(source_file_list, target_path)
